package io.hellsinger.vortex

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.flow.flow

/**
 * Creates [kotlinx.coroutines.flow.Flow] with throttle for given [periodMillis] (default: 1 sec (1000 ms))
 * It uses [conflate] operator to drop oldest values and emit only new ones
 * @param periodMillis awaits new element for given period
 * @return throttled [kotlinx.coroutines.flow.Flow]
 * **/
fun <T> Flow<T>.throttle(periodMillis: Long = 1000L) =
    flow {
        conflate().collect { value ->
            emit(value)
            delay(periodMillis)
        }
    }
